#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <cmath>
#include <iostream>
#include <string>

// 窗口大小改变时的回调函数
void framebuffer_size_callback(GLFWwindow* window, int width, int height);

// 处理用户输入
#define fresh_info() printf("\b\rg_radian_x:%.4f, g_radian_y:%.4f, g_drawArrays_count:%3d, drawMode: %s", g_radian_x, g_radian_y, g_drawArrays_count, drawModeStr.c_str())
int g_drawArrays_count = 3;
float g_radian_x = 0.0;
float g_radian_y = 0.0;
unsigned int g_drawMode = GL_TRIANGLE_FAN;
void processInput(GLFWwindow *window);

typedef float mat4[16];
mat4 g_mat4_transform_x = {0};
mat4 g_mat4_transform_y = {0};
void createRotateXMatrix(mat4 result, float radian);
void createRotateYMatrix(mat4 result, float radian);
void createRotateZMatrix(mat4 result, float radian);

int main()
{
    // 初始化GLFW
    if (!glfwInit())
    {
        std::cerr << "Failed to initialize GLFW" << std::endl;
        return -1;
    }

    // 配置GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // OS X系统需要这一行
#endif

    // 创建窗口对象
    GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cerr << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // 加载GLAD
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cerr << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    // 设置视口
    glViewport(0, 0, 800, 600);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // 顶点着色器源码
    const char *vertexShaderSource =    "#version 330 core\n"
                                        "layout (location = 0) in vec3 aPos;\n"
                                        "layout (location = 1) in vec3 aColor;\n"
                                        "uniform mat4 transformX;\n"
                                        "uniform mat4 transformY;\n"
                                        "out vec3 ourColor;\n"
                                        "void main()\n"
                                        "{\n"
                                        "   gl_Position = transformX * transformY * vec4(aPos.x, aPos.y, aPos.z, 1.0f);\n"
                                        "   ourColor = aColor;"
                                        "}\0";
    // 片段着色器源码
    const char *fragmentShaderSource =  "#version 330 core\n"
                                        "in vec3 ourColor;"
                                        "out vec4 FragColor;\n"
                                        "void main()\n"
                                        "{\n"
                                        "   FragColor = vec4(ourColor, 1.0f);\n"
                                        "}\0";

    // 创建并编译顶点着色器
    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);

    // 检查顶点着色器是否编译成功
    int success;
    char infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if(!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cerr << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }

    // 创建并编译片段着色器
    unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);

    // 检查片段着色器是否编译成功
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
    if(!success)
    {
        glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        std::cerr << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
    }

    // 创建着色器程序并链接着色器
    unsigned int shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);

    // 检查着色器程序是否链接成功
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if(!success)
    {
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        std::cerr << "ERROR::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
    }

    // 删除着色器，因为我们已经将它们链接到我们的程序中了，并且不再需要它们
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    // 设置顶点数据和配置
    float vertices_86[8][6] = {
         0.5f,  0.5f,  0.5f, 0.2f,  0.2f,  0.2f, // v0
        -0.5f,  0.5f,  0.5f, 0.8f,  0.2f,  0.2f, // v1
        -0.5f, -0.5f,  0.5f, 0.8f,  0.8f,  0.2f, // v2
         0.5f, -0.5f,  0.5f, 0.2f,  0.8f,  0.2f, // v3
         0.5f, -0.5f, -0.5f, 0.2f,  0.8f,  0.8f, // v4
         0.5f,  0.5f, -0.5f, 0.2f,  0.2f,  0.8f, // v5
        -0.5f,  0.5f, -0.5f, 0.8f,  0.2f,  0.8f, // v6
        -0.5f, -0.5f, -0.5f, 0.8f,  0.8f,  0.8f, // v7
    };

    const int drawArry_verCount_TRIANGLE_FAN = 8;
    const int index_size = 2*drawArry_verCount_TRIANGLE_FAN;
    int index[index_size] = { 0,1,2,3,4,5,6,1,
                              7,1,2,3,4,5,6,1, };

    float vertices[index_size][6];
    for (int i = 0; i < index_size; i++) {
        memcpy(vertices[i], vertices_86[index[i]], 6 * sizeof(float));
    }

    unsigned int VBO, VAO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    // 绑定VAO
    glBindVertexArray(VAO);

    // 绑定VBO并将其传递给GPU
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // 设置顶点属性指针 坐标
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    // 设置顶点属性指针 颜色
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    // 解绑VAO（为了防止后续操作意外修改它）
    glBindVertexArray(0);

    // 获取 Uniform变量-transform 的 位置
    unsigned int transXformLoc = glGetUniformLocation(shaderProgram, "transformX");
    unsigned int transYformLoc = glGetUniformLocation(shaderProgram, "transformY");

    // 循环渲染直到用户关闭窗口
    while (!glfwWindowShouldClose(window))
    {
        // 处理输入
        processInput(window);

        // 渲染指令
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // 激活着色器程序
        glUseProgram(shaderProgram);

        // 旋转矩阵传入shader
        glUniformMatrix4fv(transXformLoc, 1, GL_FALSE, g_mat4_transform_x);
        glUniformMatrix4fv(transYformLoc, 1, GL_FALSE, g_mat4_transform_y);
        // 绑定VAO（因为它包含了我们想要绘制的所有信息）
        glBindVertexArray(VAO);
        // 绘制三角形
        glDrawArrays(g_drawMode, 0,                              g_drawArrays_count);
        glDrawArrays(g_drawMode, drawArry_verCount_TRIANGLE_FAN, g_drawArrays_count);

        // 交换缓冲区并轮询IO事件
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // 清理资源
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);

    glfwTerminate();
    return 0;
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    glViewport(0, 0, width, height);
}

void processInput(GLFWwindow *window)
{
    static bool stillPress[3] = {false};
    int getkey = 0;
    static std::string drawModeStr = "GL_TRIANGLES";
    if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);

    getkey = glfwGetKey(window, GLFW_KEY_A);
    if(getkey == GLFW_PRESS && !stillPress[0]) {
        stillPress[0] = true;
        g_drawArrays_count--;
        fresh_info();
    }
    else if(getkey == GLFW_RELEASE && stillPress[0]) {
        stillPress[0] = false;
    }

    getkey = glfwGetKey(window, GLFW_KEY_Q);
    if(getkey == GLFW_PRESS && !stillPress[1]) {
        stillPress[1] = true;
        g_drawArrays_count++;
        
        fresh_info();
    }
    else if(getkey == GLFW_RELEASE && stillPress[1]) {
        stillPress[1] = false;
    }

    getkey = glfwGetKey(window, GLFW_KEY_SPACE);
    if(getkey == GLFW_PRESS && !stillPress[2]) {
        stillPress[2] = true;
        if(g_drawMode == GL_TRIANGLES) {
            g_drawMode  =  GL_TRIANGLE_STRIP;
            drawModeStr = "GL_TRIANGLE_STRIP";
        }
        else if(g_drawMode == GL_TRIANGLE_STRIP) {
            g_drawMode  =  GL_TRIANGLE_FAN;
            drawModeStr = "GL_TRIANGLE_FAN";
        }
        else if(g_drawMode == GL_TRIANGLE_FAN) {
            g_drawMode  =  GL_TRIANGLES;
            drawModeStr = "GL_TRIANGLES";
        }
        
        fresh_info();
    }
    else if(getkey == GLFW_RELEASE && stillPress[2]) {
        stillPress[2] = false;
    }


    if(glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
        g_radian_y = g_radian_y+0.0005;
        createRotateYMatrix(g_mat4_transform_y, g_radian_y);
        
        fresh_info();
    }
    if(glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
        g_radian_y = g_radian_y-0.0005;
        createRotateYMatrix(g_mat4_transform_y, g_radian_y);
        
        fresh_info();
    }
    if(glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) {
        g_radian_x = g_radian_x-0.0005;
        createRotateXMatrix(g_mat4_transform_x, g_radian_x);
        
        fresh_info();
    }
    if(glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) {
        g_radian_x = g_radian_x+0.0005;
        createRotateXMatrix(g_mat4_transform_x, g_radian_x);
        
        fresh_info();
    }
}

void createRotateXMatrix(mat4 result, float radian)
{
    float c = cos(radian);
    float s = sin(radian);

    result[0] = 1;  result[1] = 0;  result[2] = 0;  result[3] = 0;
    result[4] = 0;  result[5] = c;  result[6] = -s; result[7] = 0;
    result[8] = 0;  result[9] = s;  result[10] = c; result[11] = 0;
    result[12] = 0; result[13] = 0; result[14] = 0; result[15] = 1;
}
void createRotateYMatrix(mat4 result, float radian)
{
    float c = cos(radian);
    float s = sin(radian);

    result[0] = c;  result[1] = 0;  result[2] = -s; result[3] = 0;
    result[4] = 0;  result[5] = 1;  result[6] = 0;  result[7] = 0;
    result[8] = s;  result[9] = 0;  result[10] = c; result[11] = 0;
    result[12] = 0; result[13] = 0; result[14] = 0; result[15] = 1;
}
void createRotateZMatrix(mat4 result, float radian)
{
    float c = cos(radian);
    float s = sin(radian);

    result[0] = c;  result[1] = -s; result[2] = 0;  result[3] = 0;
    result[4] = s;  result[5] = c;  result[6] = 0;  result[7] = 0;
    result[8] = 0;  result[9] = 0;  result[10] = 1; result[11] = 0;
    result[12] = 0; result[13] = 0; result[14] = 0; result[15] = 1;
}
